//
//  PhotoCoordinator.swift
//  SwiftUILean
//
//  Created by wyknmjj on 2024/5/13.
//

import Foundation
import SwiftUI

@Observable
class PhotoCoordinator{
    var _result=initResult([] as [PhotoItem])
    var selectedItem:PhotoItem?
    //用于FLIP
    var animateView = false
    //用于最终呈现detailView
    var showDetailView = false
    
    var isLoading:Bool {
        return _result.version != _result.data.version
    }
    var result: PromiseResult<[PhotoItem]>{
        return _result.data.data
    }
    func reload(){
        Task{
            await reduceResult(getSamplePhotoItems) {
                return _result
            } setValue: { v in
                _result=v
            }
        }
    }
    
    init(){
        reload()
    }
    var count=0
    
    
    var detailScrollPosition:String?
    
    func toggleView(show:Bool){
        if(show){
            detailScrollPosition = selectedItem?.id
            detailIndicatorPosition = selectedItem?.id
            withAnimation(.easeInOut(duration:0.2),completionCriteria: .removed) {
                animateView=true
            }completion: {
                self.showDetailView=true
            }
        }else{
            showDetailView=false
            withAnimation(.easeInOut(duration: 0.2),completionCriteria: .removed) {
                animateView=false
                offset = .zero
            } completion: {
                self.resetAnimationProperties()
            }
        }
    }
    
    func resetAnimationProperties(){
        selectedItem=nil
        detailScrollPosition=nil
        offset = .zero
            dragProgress = 0
        detailIndicatorPosition=nil
    }
    
    
    func didDetailPageChanged(){
        if let updatedItem = getItemForId(id: detailScrollPosition) {
            selectedItem = updatedItem
            
            withAnimation(.easeInOut(duration: 0.1)){
                detailIndicatorPosition=updatedItem.id
            }
        }
    }
    
    var detailIndicatorPosition:String?
    func didDetailIndicatorPageChanged(){
        if let updatedItem = getItemForId(id: detailIndicatorPosition) {
            selectedItem = updatedItem
            detailScrollPosition = updatedItem.id
        }
    }
    
    
    func getItemForId(id:String?)->PhotoItem?{
        switch(result){
        case .success(data: let items):
            if let updatedItem=items.first(where: {$0.id == id}){
                return updatedItem
            }
        case .error(_):
            return nil
        }
        return nil;
    }
    
    
    var offset:CGSize = .zero
    var dragProgress:CGFloat = 0

    
    
    var visibleItem = Set<String>()
    func toggleVisible(id:String,show: Bool){
        if show {
          visibleItem =  visibleItem.union([id])
        }else{
          visibleItem =  visibleItem.subtracting([id])
        }
    }
    func itemVisible(id:String) -> Bool{
        return visibleItem.contains(id)
    }
}
